package com.tianji.learning.mq;


import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.impl.InteractionReplyServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKE_TIMES_QUEUE;

@Slf4j
@Component
@RequiredArgsConstructor
public class LikeTimesChangeListener {


    private final InteractionReplyServiceImpl replyService;

    /**
     * 监听回复点赞数变更的消息 ->修改回复表对应的点赞次数
     * @param msg 点赞数变化信息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QA_LIKE_TIMES_QUEUE, durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenReplyLikedTimesChangeMsg(LikedTimesDTO msg) {
        //1、消息健壮性判断
        if(ObjectUtil.isEmpty(msg) || ObjectUtil.isEmpty(msg.getBizId()) || ObjectUtil.isEmpty(msg.getLikedTimes())){
            log.error("点赞消息格式异常，消息：{}", msg);
        }

        //2、根据业务ID（回复表主键ID）更新点赞数
        log.info("收到点赞数变更消息，内容：{}", msg);
        InteractionReply reply = new InteractionReply().setId(msg.getBizId()).setLikedTimes(msg.getLikedTimes());
        replyService.updateById(reply);
    }
   /* public void listenReplyLikedTimesChange(List<LikedTimesDTO> likedTimesDTOs){
        log.debug("监听到回答或评论的点赞数变更");

        List<InteractionReply> list = new ArrayList<>(likedTimesDTOs.size());
        for (LikedTimesDTO dto : likedTimesDTOs) {
            InteractionReply r = new InteractionReply();
            r.setId(dto.getBizId());
            r.setLikedTimes(dto.getLikedTimes());
            list.add(r);
        }
        replyService.updateBatchById(list);
    }
*/
}
